#!/bin/bash

#set -x
APP=bdp-dcs-0.0.1-SNAPSHOT.jar

APP_DIR=`(cd "$(dirname "$0")"; pwd)`
CMD="nohup java -jar -Dloader.path=. $APP_DIR/$APP >/dev/null 2>&1 &"

Usage(){
    echo "Usage: $0 [start|stop|restart|stat]"
    echo "     start                   : start $APP"
    echo "     stop                    : stop $APP"
    echo "     restart                 : restart $APP"
    echo "     stat                    : view the status of the $APP"
    echo ""
    exit 1
}

IsAlive(){
    count=$(ps -ef | grep $APP | grep -v grep | grep -v log | wc -l)
    if (( $count >= 1 ))
    then
        echo 1
    else
        echo 0
    fi
}

Stat(){
    alive=$(IsAlive)
    if (( alive == 1 ))
    then
        echo "$APP is running."
    else
        echo "$APP process does not exist."
    fi
}

Start(){
    alive=$(IsAlive)
    if (( alive == 1 ))
    then
        echo "$APP is already running."
        exit 0
    fi

    cd $APP_DIR
    echo "$CMD"
    $CMD &
}

Stop(){
    alive=$(IsAlive)
    if (( alive == 0 ))
    then
        echo "$APP is not exist"
        return
    fi

    # 尝试 kill 4次
    for i in {0..3}
    do
        pid=$(ps -ef | grep $APP | grep -v grep | grep -v log | awk '{print $2}')
        kill $pid
        sleep 3
        alive=$(IsAlive)
        if (( alive == 0 ))
        then
            break
        fi
    done

    alive=$(IsAlive)
    if (( alive == 1 ))
    then
        echo "$APP stop fail."
    else
        echo "$APP is stoped."
    fi
}

Restart(){
    Stop
    Start
}

case $1 in
    start)
        Start
    ;;
    stop)
        Stop
    ;;
    stat)
        Stat
    ;;
    restart)
        Restart
    ;;
    *)
        Usage
    ;;
esac

